param([String]$AccessKey)

$ProgDir = "$($env:ProgramFiles)\Thingtory"

if(!(Test-Path($ProgDir))) { New-Item -ItemType Directory -Path $ProgDir | Out-Null }
(New-Object System.Net.WebClient).DownloadFile("https://thingtory.azurewebsites.net/ThingtoryWinAgent.txt", "$($ProgDir)\ThingtoryWinAgent.ps1" ) | Out-Null;

#Thanks Alex !; http://www.verboon.info/2013/12/powershell-creating-scheduled-tasks-with-powershell-version-3/
# The name of the scheduled task
$TaskName = "Thingtory"
# The description of the task
$TaskDescr = "Run Thingtory to collect Inventory data"
# The Task Action command
$TaskCommand = "powershell.exe"
# The PowerShell script to be executed
$TaskScript = "$($ProgDir)\ThingtoryWinAgent.ps1"
# The Task Action command argument
$TaskArg = "-Executionpolicy unrestricted -file ""$($TaskScript)"" -AccessKey ""$($AccessKey)""" 
# The time when the task starts, for demonstration purposes we run it 1 minute after we created the task
$TaskStartTime = [datetime]::Now.AddMinutes(1)  
# attach the Task Scheduler com object
$service = new-object -ComObject("Schedule.Service")
# connect to the local machine. 
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx
$service.Connect()
$rootFolder = $service.GetFolder("\") 
$TaskDefinition = $service.NewTask(0) 
$TaskDefinition.RegistrationInfo.Description = "$TaskDescr"
$TaskDefinition.Settings.Enabled = $true
$TaskDefinition.Settings.AllowDemandStart = $true 
$TaskDefinition.Settings.RunOnlyIfNetworkAvailable = $true
$triggers = $TaskDefinition.Triggers

#http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx
$trigger = $triggers.Create(2)  # Creates a "Daily" trigger
$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss")
$trigger.Enabled = $true 
$trigger.RandomDelay = "PT1H"
$trigger.ExecutionTimeLimit = "PT30M"
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx
$Action = $TaskDefinition.Actions.Create(0)
$action.Path = "$TaskCommand"
$action.Arguments = "$TaskArg"
#http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx
$rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) | Out-Null

Write-Host "Scheduled Task created to run Inventory daily"